const app = getApp()
const bus = require("../../../utils/bus")
const db = wx.cloud.database()


Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pickerIndex: {
      classPicker: 0,
      percentagePicker: 0,
      areaPicker: 0
    },
    classPicker: ['数码3c', '二手书籍', '生活用品', '服装配饰', '其他'],
    percentagePicker: ['几乎全新', '9成新', '8成新', '6成新', '比较旧'],
    areaPicker: ['南校区', '北校区'],
    imgs: []
    // secondHandData: {
    //   title:'',
    //   desc:'',
    //   imgs: [],
    //   price: 0,
    //   region: 0,

    //   // 1表示全新，0.5表示半新
    //   percentage: 1,
    //   area: 0
    // }
  },

  onLoad: function (options) {
    console.log(1111111)
  },

  onReady: function () {
    this.cancelModalStatus()
  },

  onShow: function () {

  },

  onHide: function () {},

  onUnload: function () {},

  onPullDownRefresh: function () {

  },

  onReachBottom: function () {

  },

  onShareAppMessage: function () {

  },

  // 取消首页中间modal的显示
  cancelModalStatus() {
    bus.emit('indexModalEvent', false)
    bus.off('indexModalEvent')
  },


  // 上传图片
  chooseImg() {
    console.log('chooseImg')
    const items = this.data.imgs
    wx.chooseImage({
      count: 6,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let tempFilePaths = res.tempFilePaths
        for (const tempFilePath of tempFilePaths) {
          items.push({
            src: tempFilePath
          })
        }

        this.setData({
          imgs: items
        })
      }
    })
  },

  // 删除图片
  removeImg(e) {
    let index = e.currentTarget.dataset.index
    console.log(index)
    let imgs = this.data.imgs

    wx.showModal({
      title: '警告',
      content: '你确定要删除该图片？',
      success: (res) => {
        if (res.confirm) {
          imgs.splice(index, 1)
          this.setData({
            imgs
          })
          wx.showToast({
            title: '删除成功',
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 上传图片到存储
  uploadPhoto(filePath) {
    return wx.cloud.uploadFile({
      cloudPath: `secondhand/${Date.now()}-${Math.floor(Math.random(0,1)*1000)}.png`,
      filePath
    })
  },

  // 预览图片
  previewImage(e) {
    const current = e.target.dataset.src
    const photos = this.data.photosNew.map(photo => photo.src)

    wx.previewImage({
      current: current.src,
      urls: photos
    })
  },


  // 并发上传图片
  formSubmit(e) {

  },



  // 新增二手发布
  async addSecondHand(e) {
    wx.showLoading({
      title: '发布中'
    })
    let data = e.detail.value
    let imgs = []
    let uploadTasks = this.data.imgs.map(item => this.uploadPhoto(item.src))
    try {
      let results = await Promise.all(uploadTasks)
      results.map(item => {
        imgs.push(item.fileID)
      })
      data = Object.assign(data,{
        imgs,
        createTime: (new Date()).getTime()
      })
      let res = await db.collection('secondhand').add({
        data
      })
      if (res._id) {
        wx.hideLoading()
        wx.showToast({
          title: '发布成功！',
        })
      }
    } catch (e) {
      wx.showToast({
        title: '啊哦，出错了',
      })
    }



    // Promise.all(uploadTasks).then(result => {
    //   console.log('图片上传成功', result)
    //   result.map(item=>{
    //     imgs.push(item.fileID)
    //   })
    //   data = Object.assign(data, {imgs})
    //   wx.hideLoading()
    // }).catch(() => {
    //   wx.hideLoading()
    //   wx.showToast({
    //     title: '上传图片错误',
    //     icon: 'error'
    //   })
    // })




    // db.collection('secondhand').add({
    //   data
    // }).then(res => {
    //   console.log(res)
    //   if (res._id) {
    //     wx.showToast({
    //       title: '发布成功！',
    //     })
    //   }
    // }).catch(err => {
    //   console.log(err)
    // })
  },


  classPickerChange(e) {
    console.log(e)
    this.setData({
      ['pickerIndex.classPicker']: parseInt(e.detail.value)
    })
  },

  percentagePickerChange(e) {
    console.log(e)
    this.setData({
      ['pickerIndex.percentagePicker']: parseInt(e.detail.value)
    })
  },

  areaPickerChange(e) {
    console.log(e)
    this.setData({
      ['pickerIndex.areaPicker']: parseInt(e.detail.value)
    })
  }
})